# 游戏管理器脚本 - 管理游戏状态和分数
extends Node

# 游戏状态
enum GameState {MENU, WAITING, PLAYING, PAUSED, GAME_OVER}
var current_state: GameState = GameState.MENU

# 分数系统
var score: int = 0
var high_score: int = 0  # 历史最高得分

# 背景音乐配置
@export_group("背景音乐设置")
@export var background_music: AudioStream  # 背景音乐
@export var music_volume: float = 0.7  # 背景音乐音量
@export var auto_play_music: bool = true  # 是否自动播放背景音乐

# UI配置
@export_group("UI设置")
@export var instruction_hide_delay: float = 3.0  # 提示文字隐藏延迟时间（秒）

# 节点引用
@onready var bird: CharacterBody2D = $Bird
@onready var score_label: Label = $UI/ScoreLabel
@onready var instructions: Label = $UI/Instructions
@onready var pipe_spawner: Node2D = $PipeSpawner
@onready var background_music_player: AudioStreamPlayer = $BackgroundMusicPlayer
@onready var instruction_timer: Timer = $InstructionTimer
@onready var game_menu: Control = $UI/GameMenu

func _ready():
	# 将游戏管理器添加到组中，以便小鸟可以调用
	add_to_group("game_manager")
	
	# 延迟一帧初始化背景音乐，确保所有节点都已准备好
	call_deferred("setup_background_music")
	
	# 连接暂停菜单按钮信号
	setup_pause_menu_buttons()
	
	# 连接主菜单按钮信号
	setup_main_menu_buttons()
	
	# 连接定时器信号
	setup_timer_signals()
	
	# 加载最高得分
	load_high_score()
	
	# 初始化游戏（显示主菜单）
	init_menu()

func setup_pause_menu_buttons():
	# 连接暂停菜单按钮信号
	if game_menu:
		var resume_button = game_menu.get_node_or_null("VBoxContainer/ResumeButton")
		var restart_button = game_menu.get_node_or_null("VBoxContainer/RestartButton")
		var quit_button = game_menu.get_node_or_null("VBoxContainer/QuitButton")
		
		if resume_button and not resume_button.pressed.is_connected(_on_resume_button_pressed):
			resume_button.pressed.connect(_on_resume_button_pressed)
		if restart_button and not restart_button.pressed.is_connected(_on_restart_button_pressed):
			restart_button.pressed.connect(_on_restart_button_pressed)
		if quit_button and not quit_button.pressed.is_connected(_on_quit_button_pressed):
			quit_button.pressed.connect(_on_quit_button_pressed)

func setup_main_menu_buttons():
	# 连接主菜单按钮信号
	if game_menu:
		var start_button = game_menu.get_node_or_null("VBoxContainer/StartButton")
		var quit_button = game_menu.get_node_or_null("VBoxContainer/QuitButton")
		
		if start_button and not start_button.pressed.is_connected(_on_start_button_pressed):
			start_button.pressed.connect(_on_start_button_pressed)
		if quit_button and not quit_button.pressed.is_connected(_on_quit_button_pressed):
			quit_button.pressed.connect(_on_quit_button_pressed)

func setup_timer_signals():
	# 连接定时器信号
	if instruction_timer:
		if not instruction_timer.timeout.is_connected(_on_instruction_timer_timeout):
			instruction_timer.timeout.connect(_on_instruction_timer_timeout)
			print("提示文字定时器信号已连接")
		else:
			print("提示文字定时器信号已存在连接")
	else:
		print("警告：InstructionTimer节点不存在")

# 最高得分相关函数
func load_high_score():
	# 从文件加载最高得分
	var save_file = FileAccess.open("user://high_score.save", FileAccess.READ)
	if save_file:
		high_score = save_file.get_var()
		save_file.close()
		print("加载最高得分: ", high_score)
	else:
		high_score = 0
		print("未找到最高得分文件，初始化为0")

func save_high_score():
	# 保存最高得分到文件
	var save_file = FileAccess.open("user://high_score.save", FileAccess.WRITE)
	if save_file:
		save_file.store_var(high_score)
		save_file.close()
		print("保存最高得分: ", high_score)
	else:
		print("错误：无法保存最高得分")

func check_and_update_high_score():
	# 检查并更新最高得分
	if score > high_score:
		high_score = score
		save_high_score()
		print("新的最高得分！: ", high_score)
		return true
	return false

func get_high_score() -> int:
	# 获取最高得分
	return high_score



func _input(event):
	# 暂停功能：按ESC键暂停游戏（但不能恢复）
	if event.is_action_pressed("ui_cancel") and event.pressed:
		if current_state == GameState.PLAYING:
			pause_game()
	
	# 在游戏结束时，按空格键重新开始
	if current_state == GameState.GAME_OVER and event.is_action_pressed("jump"):
		restart_game()
	
	# 调试：按回车键显示调试信息，按Tab键测试加载音频，按+/-调整音量
	if event.is_action_pressed("ui_accept") and event.pressed:  # 回车键显示调试信息
		debug_play_music()
	elif event.is_action_pressed("ui_focus_next") and event.pressed:  # Tab键测试加载音频
		# 尝试加载一个测试音频文件（请根据您的实际文件路径修改）
		set_background_music_temp("res://assets/audio/sfx_player_jump_01.wav")
	elif event.is_action_pressed("ui_page_up") and event.pressed:  # Page Up键增加音量
		set_music_volume(music_volume + 0.1)
	elif event.is_action_pressed("ui_page_down") and event.pressed:  # Page Down键减少音量
		set_music_volume(music_volume - 0.1)
	


func init_menu():
	# 初始化主菜单
	current_state = GameState.MENU
	score = 0
	update_score_display()
	
	# 重置小鸟
	if bird:
		bird.reset()
	
	# 停止管道生成
	if pipe_spawner:
		pipe_spawner.game_over()
	
	# 清理所有现有管道
	get_tree().call_group("pipes", "queue_free")
	
	# 不自动播放背景音乐（等待用户点击开始游戏）
	# resume_background_music()
	
	# 隐藏提示文字
	if instructions:
		instructions.visible = false
	
	# 显示统一菜单
	setup_unified_menu()
	
	print("主菜单初始化完成...")

func init_game():
	# 初始化游戏（等待玩家开始）
	current_state = GameState.WAITING
	score = 0
	update_score_display()
	
	# 重置小鸟
	if bird:
		bird.reset()
	
	# 停止管道生成
	if pipe_spawner:
		pipe_spawner.game_over()
	
	# 清理所有现有管道
	get_tree().call_group("pipes", "queue_free")
	
	# 处理背景音乐（游戏开始时恢复播放）
	resume_background_music()
	
	# 隐藏统一菜单
	if game_menu:
		game_menu.visible = false
	
	# 更新提示文本
	instructions.text = "按空格键开始游戏！\n让小鸟跳跃避开管道"
	instructions.visible = true
	
	print("游戏初始化完成，等待玩家开始...")

func start_game():
	# 从菜单开始游戏
	if current_state == GameState.MENU:
		# 从菜单直接进入游戏状态，但小鸟保持静止
		current_state = GameState.PLAYING
		print("从主菜单进入游戏...")
		
		# 重置小鸟
		if bird:
			bird.reset()
		
		# 清理所有现有管道
		get_tree().call_group("pipes", "queue_free")
		
		# 重新开始管道生成
		if pipe_spawner:
			pipe_spawner.start_game()
		
		# 恢复所有管道移动
		get_tree().call_group("pipes", "resume_moving")
		
		# 开始播放背景音乐
		play_background_music()
		
		# 隐藏统一菜单
		if game_menu:
			game_menu.visible = false
		
		# 更新提示文本
		instructions.text = "按空格键让小鸟跳跃！\n避开绿色管道"
		instructions.visible = true
		
		# 启动提示文字隐藏定时器
		start_instruction_timer()
		
		return
	
	# 开始新游戏（从等待状态）
	if current_state == GameState.WAITING:
		current_state = GameState.PLAYING
		print("游戏开始！")
		
		# 重新开始管道生成
		if pipe_spawner:
			pipe_spawner.start_game()
		
		# 恢复所有管道移动
		get_tree().call_group("pipes", "resume_moving")
		
		# 更新提示文本
		instructions.text = "按空格键让小鸟跳跃！\n避开绿色管道"
		instructions.visible = true
		
		# 启动提示文字隐藏定时器
		start_instruction_timer()

func game_over():
	# 防止重复调用
	if current_state == GameState.GAME_OVER:
		return
	
	# 游戏结束
	current_state = GameState.GAME_OVER
	
	# 停止管道生成
	if pipe_spawner:
		pipe_spawner.game_over()
	
	# 停止所有管道移动
	get_tree().call_group("pipes", "stop_moving")
	
	# 停止背景音乐
	stop_background_music()
	
	# 停止提示文字隐藏定时器
	stop_instruction_timer()
	
	# 隐藏统一菜单
	if game_menu:
		game_menu.visible = false
	
	# 检查并更新最高得分
	var is_new_high_score = check_and_update_high_score()
	
	# 显示游戏结束信息
	var game_over_text = "游戏结束！\n最终分数: " + str(score)
	if is_new_high_score:
		game_over_text += "\n🎉 新纪录！"
	else:
		game_over_text += "\n最高分: " + str(high_score)
	
	instructions.text = game_over_text
	instructions.visible = true
	
	print("游戏结束！最终分数: " + str(score) + ", 最高分: " + str(high_score))
	
	# 直接返回主菜单
	restart_game()

func restart_game():
	# 重新开始游戏
	print("重新开始游戏...")
	
	# 如果当前是暂停状态，先恢复所有系统
	if current_state == GameState.PAUSED:
		# 恢复小鸟移动
		if bird:
			bird.set_physics_process(true)
		
		# 恢复管道生成
		if pipe_spawner:
			pipe_spawner.set_physics_process(true)
		
		# 恢复所有管道移动
		get_tree().call_group("pipes", "resume_moving")
		
		# 隐藏统一菜单
		if game_menu:
			game_menu.visible = false
	
	# 清理所有现有管道
	get_tree().call_group("pipes", "queue_free")
	
	# 隐藏游戏结束提示
	if instructions:
		instructions.visible = false
	
	# 回到主菜单
	init_menu()

func pause_game():
	# 暂停游戏
	if current_state == GameState.PLAYING:
		current_state = GameState.PAUSED
		
		# 暂停小鸟移动
		if bird:
			bird.set_physics_process(false)
		
		# 暂停管道生成
		if pipe_spawner:
			pipe_spawner.set_physics_process(false)
		
		# 暂停所有管道移动
		get_tree().call_group("pipes", "stop_moving")
		
		# 暂停背景音乐
		pause_background_music()
		
		# 停止提示文字隐藏定时器
		stop_instruction_timer()
		
		# 显示统一菜单
		setup_unified_menu()
		
		# 更新提示文本
		instructions.text = "游戏已暂停"
		instructions.visible = true
		
		print("游戏已暂停")

func resume_game():
	# 恢复游戏
	if current_state == GameState.PAUSED:
		current_state = GameState.PLAYING
		
		# 恢复小鸟移动
		if bird:
			bird.set_physics_process(true)
		
		# 恢复管道生成
		if pipe_spawner:
			pipe_spawner.set_physics_process(true)
		
		# 恢复所有管道移动
		get_tree().call_group("pipes", "resume_moving")
		
		# 恢复背景音乐
		resume_background_music()
		
		# 隐藏统一菜单
		if game_menu:
			game_menu.visible = false
		
		# 更新提示文本
		instructions.text = "按空格键让小鸟跳跃！\n避开绿色管道"
		instructions.visible = true
		
		# 重新启动提示文字隐藏定时器
		start_instruction_timer()
		
		print("游戏已恢复")

func add_score(points: int = 1):
	# 增加分数
	if current_state == GameState.PLAYING:
		score += points
		update_score_display()
		print("得分！当前分数: " + str(score))

func update_score_display():
	# 更新分数显示
	if score_label:
		score_label.text = "分数: " + str(score) + " | 最高分: " + str(high_score)

func setup_background_music():
	print("=== 开始初始化背景音乐 ===")
	print("background_music: ", background_music)
	print("background_music_player: ", background_music_player)
	print("auto_play_music: ", auto_play_music)
	print("music_volume: ", music_volume)
	
	# 检查节点引用
	if not background_music_player:
		print("错误：BackgroundMusicPlayer节点引用为空")
		# 尝试重新获取节点引用
		background_music_player = get_node_or_null("BackgroundMusicPlayer")
		if background_music_player:
			print("成功重新获取BackgroundMusicPlayer节点引用")
		else:
			print("错误：无法找到BackgroundMusicPlayer节点")
			return
	
	# 设置背景音乐
	if background_music and background_music_player:
		print("配置背景音乐...")
		background_music_player.stream = background_music
		background_music_player.volume_db = linear_to_db(music_volume)
		
		# 尝试设置音乐总线，如果不存在则使用默认总线
		if AudioServer.get_bus_index("Music") != -1:
			background_music_player.bus = "Music"
			print("使用Music音频总线")
		else:
			background_music_player.bus = "Master"
			print("Music总线不存在，使用Master总线")
		
		# 如果启用自动播放，开始播放背景音乐
		if auto_play_music:
			background_music_player.play()
			print("开始播放背景音乐，音量: ", music_volume)
		else:
			print("自动播放已禁用")
	elif background_music:
		print("警告：背景音乐已配置但缺少BackgroundMusicPlayer节点")
	elif background_music_player:
		print("警告：BackgroundMusicPlayer节点存在但未配置背景音乐")
		print("请检查Inspector面板中的'背景音乐设置'组")
	else:
		print("调试：background_music = ", background_music, ", background_music_player = ", background_music_player)
	
	print("=== 背景音乐初始化完成 ===")

# 背景音乐控制函数
func play_background_music():
	# 播放背景音乐
	if background_music_player:
		if not background_music_player.playing:
			background_music_player.play()
			print("播放背景音乐")
		else:
			print("背景音乐已在播放中")
	else:
		print("错误：BackgroundMusicPlayer节点不存在")

func stop_background_music():
	# 停止背景音乐
	if background_music_player and background_music_player.playing:
		background_music_player.stop()
		print("停止背景音乐")

func pause_background_music():
	# 暂停背景音乐
	if background_music_player and background_music_player.playing:
		background_music_player.stream_paused = true
		print("暂停背景音乐")

func resume_background_music():
	# 恢复背景音乐
	if background_music_player and background_music_player.stream_paused:
		background_music_player.stream_paused = false
		print("恢复背景音乐")

func set_music_volume(volume: float):
	# 设置背景音乐音量
	music_volume = clamp(volume, 0.0, 1.0)
	if background_music_player:
		background_music_player.volume_db = linear_to_db(music_volume)
		print("设置背景音乐音量: ", music_volume)

# 调试函数：手动触发背景音乐播放
func debug_play_music():
	print("=== 背景音乐调试信息 ===")
	print("background_music: ", background_music)
	print("background_music_player: ", background_music_player)
	print("auto_play_music: ", auto_play_music)
	print("music_volume: ", music_volume)
	
	# 检查节点引用
	if not background_music_player:
		print("错误：BackgroundMusicPlayer节点引用为空")
		background_music_player = get_node_or_null("BackgroundMusicPlayer")
		if background_music_player:
			print("成功重新获取BackgroundMusicPlayer节点引用")
		else:
			print("错误：无法找到BackgroundMusicPlayer节点")
			return
	
	if background_music_player:
		print("AudioStreamPlayer状态:")
		print("- stream: ", background_music_player.stream)
		print("- playing: ", background_music_player.playing)
		print("- volume_db: ", background_music_player.volume_db)
		print("- bus: ", background_music_player.bus)
		
		# 检查是否有音频流
		if not background_music_player.stream:
			print("警告：AudioStreamPlayer没有设置音频流")
			if background_music:
				print("尝试重新设置音频流...")
				background_music_player.stream = background_music
				print("音频流设置完成")
	
	# 尝试手动播放
	play_background_music()

# 手动重新初始化背景音乐
func reinitialize_background_music():
	print("=== 重新初始化背景音乐 ===")
	setup_background_music()

# 临时设置背景音乐（用于测试）
func set_background_music_temp(audio_path: String):
	print("临时设置背景音乐: ", audio_path)
	var audio_stream = load(audio_path)
	if audio_stream:
		background_music = audio_stream
		print("背景音乐加载成功")
		# 重新初始化
		setup_background_music()
	else:
		print("错误：无法加载音频文件: ", audio_path)

# 暂停菜单按钮信号处理
func _on_resume_button_pressed():
	resume_game()

func _on_restart_button_pressed():
	restart_game()

func _on_quit_button_pressed():
	get_tree().quit()

# 主菜单按钮信号处理
func _on_start_button_pressed():
	start_game()

# 提示文字定时器相关函数
func start_instruction_timer():
	# 启动提示文字隐藏定时器
	if instruction_timer:
		instruction_timer.wait_time = instruction_hide_delay
		instruction_timer.start()
		print("启动提示文字隐藏定时器，延迟时间: ", instruction_hide_delay, " 秒")

func stop_instruction_timer():
	# 停止提示文字隐藏定时器
	if instruction_timer and instruction_timer.time_left > 0:
		instruction_timer.stop()
		print("停止提示文字隐藏定时器")

func _on_instruction_timer_timeout():
	# 定时器超时，隐藏提示文字
	if instructions:
		instructions.visible = false
		print("提示文字已自动隐藏")

func setup_unified_menu():
	# 显示统一菜单，根据游戏状态调整按钮
	if game_menu:
		var start_button = game_menu.get_node_or_null("VBoxContainer/StartButton")
		var resume_button = game_menu.get_node_or_null("VBoxContainer/ResumeButton")
		var restart_button = game_menu.get_node_or_null("VBoxContainer/RestartButton")
		var settings_button = game_menu.get_node_or_null("VBoxContainer/SettingsButton")
		var quit_button = game_menu.get_node_or_null("VBoxContainer/QuitButton")
		var title_label = game_menu.get_node_or_null("VBoxContainer/TitleLabel")
		var high_score_label = game_menu.get_node_or_null("VBoxContainer/HighScoreLabel")
		
		if current_state == GameState.MENU:
			# 主菜单状态：只显示开始游戏和退出游戏
			if title_label:
				title_label.text = "Flappy Bird"
			if high_score_label:
				high_score_label.text = "最高分: " + str(high_score)
				high_score_label.visible = true
			if start_button:
				start_button.visible = true
			if resume_button:
				resume_button.visible = false
			if restart_button:
				restart_button.visible = false
			if settings_button:
				settings_button.visible = false
			if quit_button:
				quit_button.visible = true
		elif current_state == GameState.PAUSED:
			# 暂停状态：只显示继续游戏和退出游戏
			if title_label:
				title_label.text = "游戏暂停"
			if high_score_label:
				high_score_label.visible = false
			if start_button:
				start_button.visible = false
			if resume_button:
				resume_button.visible = true
			if restart_button:
				restart_button.visible = false
			if settings_button:
				settings_button.visible = false
			if quit_button:
				quit_button.visible = true
		
		game_menu.visible = true
